package com.lcicl.reggie.service.impl;
/*
  Date: 2023/10/23
  Author: Luochao
  Description:
*/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcicl.reggie.entity.ShoppingCart;
import com.lcicl.reggie.mapper.ShoppingCartMapper;
import com.lcicl.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {

        //先查询购物车有无该商品
        ShoppingCart exist = this.selectOne(shoppingCart);

        if (exist == null) {    //没有该商品
            exist = shoppingCart;
            this.save(exist);
        } else {       //存在，数量求和
            exist.setNumber(exist.getNumber() + shoppingCart.getNumber());
            this.updateById(exist);
        }
        return exist;
    }


    /**
     * 查询是否有一份以上的购物车记录，并返回查到的记录
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart selectOne(ShoppingCart shoppingCart) {
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());

        return this.getOne(shoppingCartLambdaQueryWrapper);
    }

    /**
     * 减少商品
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart decrease(ShoppingCart shoppingCart) {
        Integer number = shoppingCart.getNumber();
        if (number == 1) {
            this.removeById(shoppingCart);
            System.out.println(shoppingCart);
        } else {
            shoppingCart.setNumber(number - 1);
            this.updateById(shoppingCart);
            System.out.println(shoppingCart);
        }

        return shoppingCart;
    }
}
